<template>
  <view class="container">
    <u-sticky>
      <view class="header">
        <view class="search-section">
          <u-search placeholder="搜索商家、美食、服务..." v-model="listQuery.keyword" @search="handleSearch" @change="handleSearch"></u-search>
          <view class="filter-btn" @click="showFilter">
            <u-icon name="list" color="#0ea5e9" size="20"></u-icon>
          </view>
        </view>
        <!-- 快速筛选标签 -->
        <view class="quick-filters">
          <u-tag v-for="filter in quickFilters" :key="filter.key" :text="filter.name" :type="selectedQuickFilter === filter.key ? 'primary' : 'info'"
            :plain="selectedQuickFilter !== filter.key" shape="circle" @click="handleQuickFilter(filter.key)"></u-tag>
        </view>
      </view>
    </u-sticky>

    <!-- 商家列表 -->
    <mescroll-body ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback" :fixed="false" :top="10">
      <view class="merchant-list">
        <view class="merchant-card" v-for="(item, index) in list" :key="item.id" @click="handleNavInfo(item)">
          <!-- 商家图片区域 -->
          <view class="card-image">
            <u-image :src="item.face" width="200rpx" height="280rpx" border-radius="16rpx" mode="aspectFill"></u-image>
            <!-- 营业状态 -->
            <view class="business-status" :class="item.isEnabled ? 'open' : 'closed'">
              <text class="status-text">{{ item.isEnabled ? '营业中' : '已打烊' }}</text>
            </view>
            <!-- 距离标签 -->
            <view class="distance-tag" v-if="item.distance">
              <text class="distance-text">{{ item.distance }}-- km</text>
            </view>
          </view>

          <!-- 商家信息区域 -->
          <view class="card-content">
            <!-- 商家名称和评分 -->
            <view class="merchant-header">
              <text class="merchant-name">{{ item.name }}</text>
              <view class="merchant-rating">
                <u-rate :value="item.rating" :count="5" :size="14" active-color="#fbbf24" inactive-color="#e5e7eb" :readonly="true"></u-rate>
                <text class="rating-text">{{ item.rating }}</text>
                <text class="review-count" v-if="item.reviewCount">({{ item.reviewCount }})</text>
              </view>
            </view>

            <!-- 商家标签 -->
            <view class="merchant-tags">
              <u-tag v-for="tag in item.tags" :key="tag" :text="tag" plain bg-color="#e0f2fe" color="#0369a1" border-color="transparent" size="mini"
                shape="circle" :custom-style="{ marginRight: '8rpx', marginBottom: '8rpx' }"></u-tag>
            </view>

            <!-- 地址信息 -->
            <view class="merchant-address">
              <u-icon name="map" color="#64748b" size="14"></u-icon>
              <text class="address-text">{{ item.address }}</text>
            </view>

            <!-- 营业时间 -->
            <view class="business-hours">
              <u-icon name="clock" color="#64748b" size="14"></u-icon>
              <text class="hours-text">{{ item.businessHours }}</text>
            </view>

            <!-- 人均消费 -->
            <view class="average-price" v-if="item.averageCost">
              <u-icon name="rmb-circle" color="#059669" size="14"></u-icon>
              <text class="price-text">人均 ¥{{ item.averageCost }}</text>
            </view>

            <!-- 底部操作区 -->
            <view class="merchant-footer">
              <view class="contact-info">
                <text class="phone-text">{{ item.phone }}</text>
              </view>
              <view class="action-btns">
                <view @click.stop="callMerchant(item)">
                  <u-button type="info" size="mini" :plain="true" shape="circle" icon="phone" text="电话" :custom-style="callBtnStyle">
                  </u-button>
                </view>
                <view @click.stop="navigateToMerchant(item)">
                  <u-button type="primary" size="mini" shape="circle" icon="map" text="导航" :custom-style="navBtnStyle">
                  </u-button>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </mescroll-body>

    <!-- 高级筛选弹窗 -->
    <u-popup :show="showFilterModal" mode="bottom" border-radius="32" :safe-area-inset-bottom="true">
      <view class="filter-content">
        <view class="filter-header">
          <text class="filter-title">筛选条件</text>
          <u-icon name="close" color="#94a3b8" size="20" @click="hideFilter"></u-icon>
        </view>

        <view class="filter-body">
          <!-- 商家类型筛选 -->
          <view class="filter-section">
            <text class="section-title">商家类型</text>
            <view class="filter-options">
              <u-tag v-for="type in merchantTypes" :key="type" :text="type" :type="selectedType === type ? 'primary' : 'info'"
                :plain="selectedType !== type" shape="circle" @click="handleTypeSelect(type)"></u-tag>
            </view>
          </view>

          <!-- 距离筛选 -->
          <view class="filter-section">
            <text class="section-title">距离范围</text>
            <view class="filter-options">
              <u-tag v-for="distance in distanceOptions" :key="distance" :text="distance" :type="selectedDistance === distance ? 'primary' : 'info'"
                :plain="selectedDistance !== distance" shape="circle" @click="handleDistanceSelect(distance)"></u-tag>
            </view>
          </view>

          <!-- 评分筛选 -->
          <view class="filter-section">
            <text class="section-title">评分要求</text>
            <view class="rating-filter">
              <view class="rating-option" v-for="rating in ratingOptions" :key="rating.value" :class="{ active: selectedRating === rating.value }"
                @click="selectedRating = selectedRating === rating.value ? '' : rating.value">
                <u-rate :value="rating.value" :count="5" :size="16" active-color="#fbbf24" inactive-color="#e5e7eb" :readonly="true"></u-rate>
                <text class="rating-label">{{ rating.label }}</text>
              </view>
            </view>
          </view>
        </view>

        <view class="filter-footer">
          <u-button type="info" :plain="true" shape="circle" :custom-style="resetBtnStyle" @click="resetFilter">
            重置
          </u-button>
          <u-button type="primary" shape="circle" :custom-style="confirmBtnStyle" @click="confirmFilter">
            确定
          </u-button>
        </view>
      </view>
    </u-popup>

    <!-- 提示组件 -->
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
  import MescrollMixin from "@/libs/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";


  export default {
    mixins: [MescrollMixin],
    data() {
      return {
        mescroll: null,
        downOption: {
          use: true,
          auto: true
        },
        upOption: {
          page: {
            num: 0,
            size: 10,
            time: null
          },
          empty: {
            use: true,
            icon: null,
            tip: "暂无数据",
            fixed: false,
            top: "560rpx",
          },
          textNoMore: '没有更多数据',
          toTop: {
            duration: 300,
            supportTap: false,
            btnClick: null
          }
        },
        listQuery: {
          page: 1,
          pageSize: 10,
          keyword: ''
        },
        list: [],
        showFilterModal: false,
        selectedQuickFilter: '',
        selectedType: '',
        selectedDistance: '',
        selectedRating: '',
        isLoading: false,

        // 快速筛选选项
        quickFilters: [
          { key: 'all', name: '全部' },
          { key: 'food', name: '美食' },
          { key: 'shopping', name: '购物' },
          { key: 'entertainment', name: '娱乐' },
          { key: 'service', name: '服务' }
        ],

        // 商家类型选项
        merchantTypes: ['餐饮美食', '购物商场', '休闲娱乐', '生活服务', '酒店住宿', '汽车服务', '教育培训', '医疗健康'],

        // 距离选项
        distanceOptions: ['1公里内', '3公里内', '5公里内', '10公里内', '不限距离'],

        // 评分选项
        ratingOptions: [
          { value: 5, label: '5星' },
          { value: 4, label: '4星以上' },
          { value: 3, label: '3星以上' },
          { value: 2, label: '2星以上' }
        ],

        // 按钮样式
        callBtnStyle: {
          height: '56rpx',
          fontSize: '24rpx',
          marginRight: '16rpx'
        },
        navBtnStyle: {
          height: '56rpx',
          fontSize: '24rpx',
          background: 'linear-gradient(135deg, #0ea5e9, #06b6d4)',
          border: 'none'
        },
        resetBtnStyle: {
          flex: '1',
          marginRight: '24rpx'
        },
        confirmBtnStyle: {
          flex: '1',
          background: 'linear-gradient(135deg, #0ea5e9, #06b6d4)',
          border: 'none'
        }
      }
    },
    onLoad() {
      // 获取系统信息，计算头部高度 
    },
    methods: {
      // mescroll初始化
      mescrollInit(mescroll) {
        this.mescroll = mescroll
      },
      upCallback(options) {
        this.listQuery.page = options.num
        this.listQuery.pageSize = options.size
        // console.log(`正在加载${options.num}页数据`)
        this.fetchData()
      },
      // 下拉刷新的回调 (mixin默认resetUpScroll)
      downCallback() {
        this.listQuery.page = 1
        if (this.mescroll.optUp.use) {
          this.mescroll.resetUpScroll()
        } else {
          setTimeout(() => {
            this.mescroll.endSuccess()
          }, 500)
        }
      },
      mescrollInit(mescroll) {
        this.mescroll = mescroll
      },
      handleSearch() {
        this.mescroll.resetUpScroll()
      },
      fetchData() {
        uni.$u.http.get('/api/shop/list', { params: this.listQuery }).then(response => {
          let { code, message, result } = response.data
          if (code != 200) {
            this.mescroll.endErr()
            this.$u.toast(message)
            return
          }
          let { items, page, total, totalPages } = result
          if (result.page == 1) {
            this.list = new Array()
          }
          for (let item of items) {
            if (item.imageUrls) {
              let imgs = JSON.parse(item.imageUrls)
              item.face = imgs[0]
            }
            this.list.push(item)
          }
          this.mescroll.endSuccess(items.length, page < totalPages)
        }).catch(err => {
          console.error('获取招聘信息失败:', err)
          this.mescroll.endErr()
        })
      },
      handleSearch() {
        // 搜索
        console.log('搜索关键词:', this.searchKeyword)
        this.mescroll.resetUpScroll()
      },
      handleNavInfo(item) {
        // 跳转商家详情
        console.log('查看商家详情:', item.name)
        this.$u.route({
          url: '/pages/shop/detail',
          params: {
            id: item.id
          }
        })

      },

      handleQuickFilter(key) {
        // 快速筛选
        this.selectedQuickFilter = this.selectedQuickFilter === key ? '' : key
        console.log('快速筛选:', key)
        this.mescroll.resetUpScroll()
      },

      showFilter() {
        // 显示筛选
        this.showFilterModal = true
      },
      hideFilter() {

        // 隐藏筛选
        this.showFilterModal = false
      },

      handleTypeSelect(type) {
        // 类型选择
        this.selectedType = this.selectedType === type ? '' : type
      },

      handleDistanceSelect(distance) {
        // 距离选择
        this.selectedDistance = this.selectedDistance === distance ? '' : distance
      },

      resetFilter() {
        // 重置筛选
        this.selectedType = ''
        this.selectedDistance = ''
        this.selectedRating = ''
      },

      confirmFilter() {
        // 确认筛选
        console.log('筛选条件:', {
          type: this.selectedType,
          distance: this.selectedDistance,
          rating: this.selectedRating
        })
        this.hideFilter()
        this.mescroll.resetUpScroll()
      },
      callMerchant(item) {
        // 拨打电话
        console.log('拨打电话:', item.phone)
        uni.makePhoneCall({
          phoneNumber: item.phone,
          success: () => {
            console.log('拨打电话成功')
          },
          fail: (err) => {
            console.error('拨打电话失败:', err)
            this.$refs.uToast.show({
              message: '拨打失败',
              type: 'error'
            })
          }
        })
      },
      navigateToMerchant(item) {

        // 导航到商家
        console.log('导航到商家:', item.name)
        // 这里可以调用地图导航API
        this.$refs.uToast.show({
          message: '正在打开导航',
          type: 'success'
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .container {
    min-height: 100vh;
    background: #f8fafc;
  }

  .header {
    position: sticky;
    background: white;
    padding: 24rpx;
    border-bottom: 1rpx solid #f0f0f0;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);

    .search-section {
      display: flex;
      align-items: center;
      gap: 20rpx;
      margin-bottom: 24rpx;

      .filter-btn {
        width: 72rpx;
        height: 72rpx;
        background: #e0f2fe;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s ease;

        &:active {
          transform: scale(0.95);
          background: #bae6fd;
        }
      }
    }

  }

  .quick-filters {
    display: flex;
    align-items: center;
    overflow-x: auto;
    padding-bottom: 8rpx;
    gap: 10px;
  }

  .merchant-list {
    padding: 0rpx 32rpx;
  }

  .merchant-card {
    background: white;
    border-radius: 24rpx;
    margin-bottom: 32rpx;
    padding: 32rpx;
    box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
    border: 1rpx solid #f1f5f9;
    display: flex;
    gap: 24rpx;
    transition: all 0.3s ease;

    &:active {
      transform: translateY(4rpx);
      box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.12);
    }
  }

  .card-image {
    position: relative;
    flex-shrink: 0;

    .business-status {
      position: absolute;
      top: 8rpx;
      left: 8rpx;
      padding: 6rpx 12rpx;
      border-radius: 12rpx;

      &.open {
        background: linear-gradient(135deg, #10b981, #059669);
      }

      &.closed {
        background: linear-gradient(135deg, #ef4444, #dc2626);
      }

      .status-text {
        color: white;
        font-size: 20rpx;
        font-weight: 500;
      }
    }

    .distance-tag {
      position: absolute;
      bottom: 8rpx;
      right: 8rpx;
      background: rgba(0, 0, 0, 0.6);
      color: white;
      padding: 6rpx 12rpx;
      border-radius: 12rpx;
      backdrop-filter: blur(10rpx);

      .distance-text {
        font-size: 20rpx;
        font-weight: 500;
      }
    }
  }

  .card-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 16rpx;
  }

  .merchant-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .merchant-name {
      flex: 1;
      font-size: 32rpx;
      font-weight: 600;
      color: #1e293b;
      margin-right: 16rpx;
      line-height: 1.3;
    }

    .merchant-rating {
      display: flex;
      align-items: center;
      gap: 6rpx;
      flex-shrink: 0;

      .rating-text {
        font-size: 24rpx;
        color: #64748b;
        font-weight: 500;
      }

      .review-count {
        font-size: 22rpx;
        color: #94a3b8;
      }
    }
  }

  .merchant-tags {
    display: flex;
    flex-wrap: wrap;
  }

  .merchant-address,
  .business-hours,
  .average-price {
    display: flex;
    align-items: center;
    gap: 8rpx;

    .address-text,
    .hours-text,
    .price-text {
      font-size: 24rpx;
      color: #64748b;
    }

    .price-text {
      color: #059669;
      font-weight: 500;
    }
  }

  .merchant-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .phone-text {
      font-size: 24rpx;
      color: #64748b;
    }

    .action-btns {
      display: flex;
      align-items: center;
    }
  }

  .filter-content {
    .filter-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 32rpx;
      border-bottom: 1rpx solid #f1f5f9;

      .filter-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #1e293b;
      }
    }

    .filter-body {
      padding: 32rpx;
      max-height: 60vh;
      overflow-y: auto;

      .filter-section {
        margin-bottom: 48rpx;

        .section-title {
          display: block;
          font-size: 28rpx;
          font-weight: 600;
          color: #1e293b;
          margin-bottom: 24rpx;
        }

        .filter-options {
          display: flex;
          flex-wrap: wrap;
        }

        .rating-filter {
          .rating-option {
            display: flex;
            align-items: center;
            gap: 16rpx;
            padding: 16rpx 24rpx;
            border: 2rpx solid #e2e8f0;
            border-radius: 16rpx;
            margin-bottom: 16rpx;
            transition: all 0.3s ease;

            &.active {
              border-color: #0ea5e9;
              background: #f0f9ff;
            }

            .rating-label {
              font-size: 26rpx;
              color: #64748b;
            }
          }
        }
      }
    }

    .filter-footer {
      display: flex;
      gap: 24rpx;
      padding: 32rpx;
      border-top: 1rpx solid #f1f5f9;
    }
  }
</style>